-- StringTools
-- 字符串扩展函数
 
-- 分割字符串
function string.split(str, delim, maxNb)   
    -- Eliminate bad cases...   
    if string.find(str, delim) == nil then  
        return { str }  
    end  
    if maxNb == nil or maxNb < 1 then  
        maxNb = 0    -- No limit   
    end  
    local result = {}  
    local pat = "(.-)" .. delim .. "()"   
    local nb = 0  
    local lastPos   
    for part, pos in string.gmatch(str, pat) do  
        nb = nb + 1  
        result[nb] = part   
        lastPos = pos   
        if nb == maxNb then break end  
    end  
    -- Handle the last field   
    if nb ~= maxNb then  
        result[nb + 1] = string.sub(str, lastPos)   
    end  
    return result   
end  

-- 把字符串分割成数字
function string.splitToNumber(str, delim, maxNb)
    local result = string.split(str, delim, maxNb)
    for i = 1,#result do
        result[i] = tonumber(result[i])
    end
    return result
end

-- DateTools
-- 日期函数
date = {}

-- 获得当前日期的字符串
function date.getDateString()
    return os.date("%c")
end

-- 重置随机数种子
function math.newRandomseed()
    math.randomseed(os.clock() + 77 * ElapsedTime)
    math.random()
    math.random()
    math.random()
end

-- 随机数类
Random = class()
Random.generating = false

-- 初始化随机数生成器(用种子)
function Random:init(seed)
    self.seed = seed or math.floor(math.random() * 2928437 - math.random() * 1373747)
    self.seed = (self.seed * 37 + 137) % 394243577
    self.generating = false
    self.genCount = 0
end

-- 开始生成随机数
function Random:begin()
    if Random.generating == true then
        error("A Random is generating!")
    end
    self.generating = true
    self.genCount = 0
    math.randomseed(self.seed)
    math.random()
    math.random()
    math.random()
end

-- 停止生成随机数
function Random:End()
    self.generating = false
    Random.generating = false
end

-- 生成随机整数
function Random:rndInt(min,max)
    self.genCount = self.genCount + 1
    if self.genCount > 20 then
        math.randomseed(self.seed)
        self.seed = (self.seed + 137) % 394243577
        self.genCount = 0
    end
    return math.random(min,max)
end

-- 返回一个从0到1的随机小数
function Random:rndDouble()
    self.genCount = self.genCount + 1
    if self.genCount > 20 then
        math.randomseed(self.seed)
        self.seed = (self.seed + 137) % 394243577
        self.genCount = 0
    end
    return math.random()
end
